package net.heartbeat.source.senders;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import net.heartbeat.source.HeartbeatSender;

/**
 * 把心跳包用TCP协议发送到指定的主机上
 * 
 * @author Bai Yu
 *
 */
public class TcpSender implements HeartbeatSender {
	public TcpSender(String targetIp, int targetPort) {
		this.targetIp = targetIp;
		this.targetPort = targetPort;
	}

	// 创建的OutputStream（Socket.getOutputStream()）没有关闭，故产生该警告
	// 该警告可忽略，因为：
	// OutputStream被返回给调用者，必须保持打开才能供调用者使用
	// 使用完毕后，应由调用者关闭该资源
	@SuppressWarnings("resource")
	@Override
	public OutputStream getOutputStream() throws IOException {
		Socket client = new Socket(targetIp, targetPort);

		try {
			// 引用javadoc：Socket.getOutputStream()
			// "Closing the returned OutputStream will close the associated
			// socket"
			return client.getOutputStream();
		} catch (IOException e) {
			try {
				client.close();
			} catch (IOException e1) {
			}

			throw e;
		}
	}

	private String targetIp;
	private int targetPort;
}
